package mm.test.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.logging.Logger;

/**
 * HttpClient工具类
 *
 */
@Slf4j
public class   HttpClientUtils {

    private static RequestConfig requestConfig = null;
    //请求超时时间,这个时间定义了socket读数据的超时时间，也就是连接到服务器之后到从服务器获取响应数据需要等待的时间,发生超时，会抛出SocketTimeoutException异常。
    private static final int SOCKET_TIME_OUT = 60000;
    //连接超时时间,这个时间定义了通过网络与服务器建立连接的超时时间，也就是取得了连接池中的某个连接之后到接通目标url的连接等待时间。发生超时，会抛出ConnectionTimeoutException异常
    private static final int CONNECT_TIME_OUT = 60000;
    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 30).setConnectTimeout(1000 * 30).build();
    }
    public static Object postForAPP(String url,  Map<String, Object> param, Map<String, String> headers) throws Exception {
        //目前HttpClient最新版的实现类为CloseableHttpClient
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpEntity entity=null;
        try {
            if(param != null) {
                //建立Request的对象，一般用目标url来构造，Request一般配置addHeader、setEntity、setConfig
                HttpPost req = new HttpPost(url);
                //entity=new UrlEncodedFormEntity(createParam(param), Consts.UTF_8);

                entity=new StringEntity(JSONObject.toJSONString(param), Consts.UTF_8);
                //setHeader,添加头文件
                Set<String> keys = headers.keySet();
                for (String key : keys) {
                    req.setHeader(key, headers.get(key).toString());
                }
                //setConfig,添加配置,如设置请求超时时间,连接超时时间
                RequestConfig reqConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
                req.setConfig(reqConfig);
                //setEntity,添加内容
                req.setEntity(entity);
                //执行Request请求,CloseableHttpClient的execute方法返回的response都是CloseableHttpResponse类型
                //其常用方法有getFirstHeader(String)、getLastHeader(String)、headerIterator（String）取得某个Header name对应的迭代器、getAllHeaders()、getEntity、getStatus等
                response = client.execute(req);
                entity =  response.getEntity();
                //用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
                String result= EntityUtils.toString(entity, "UTF-8");
                Object ob=JSONObject.parseObject(result,Object.class);
                log.error("-------------------------"+result+"-------------");
                if(response.getStatusLine().getStatusCode()==200){
                    log.error(result+"-----------success------------------");
                    return ob;
                }else{
                    log.error(response.getStatusLine().getStatusCode()+"------------------fail-----------");
                    return null;
                }
            }
            return null;
        } catch(Exception e) {
            log.error("--------------------------post error: ", e);
            throw new Exception();
        }finally{
            //一定要记得把entity fully consume掉，否则连接池中的connection就会一直处于占用状态
            EntityUtils.consume(entity);
            log.error("---------------------------finally-------------");
            System.out.println("---------------------------------------------------");
        }
    }


    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static String httpGet(String url, Map<String, Object> params, Map<String, String> heads) {
        // get请求返回结果
        JSONObject jsonResult = null;
        String strResult = "";
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        //拼接参数
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            if (url.contains("?")) {

                url += "&" + key + "=" + value;
            } else {
                url += "?" + key + "=" + value;
            }
        }
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        try {

            //拼接头
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                request.setHeader(key, value);
            }
            CloseableHttpResponse response = client.execute(request);

            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                strResult = EntityUtils.toString(entity, "utf-8");
            } else {
                jsonResult = new JSONObject();
                jsonResult.put("posterror", "");
                log.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            log.error("get请求提交失败:" + url, e);

        } finally {
            request.releaseConnection();
        }
        return strResult;
    }



}